/*
 * Usage: copy src_file dest_file
 */

#include "command.h"

int _copy(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc != 3) {
		fprintf(stderr, "Usage: copy src_file dest_file\n");
		return -1;
	}

	int src_fd, dest_fd; 		/* file descriptor */
	ssize_t num_read;
	int openflags; 				/* dest_file */
	mode_t file_perms; 			/* the permissions of creating file */
	const char *src_pathname = argv[1];
	const char *dest_pathname = argv[2];
	char buf[BUF_SIZE]; 		/* store the content read from src_file */

	/* open src_file and dest_file */
	src_fd = open(src_pathname, O_RDONLY);
	if (src_fd == -1) {
		fprintf(stderr, "copy: open source file error!\n");
		return -1;
	}

	openflags = O_CREAT | O_WRONLY | O_TRUNC;
	file_perms = S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP 
				| S_IROTH | S_IWOTH; 		/* rw-rw-rw- */
	dest_fd = open(dest_pathname, openflags, file_perms);
	if (dest_fd == -1) {
		fprintf(stderr, "copy: open destination file error!\n");
		return -1;
	}

	/* read from src_file and wirte it to dest_file */
	while ((num_read = read(src_fd, buf, BUF_SIZE)) > 0) {
		if (write(dest_fd, buf, num_read) != num_read) {
			fprintf(stderr, "copy: write error\n");
			return -1;
		}
	}
	if (num_read == -1) {
		fprintf(stderr, "copy: read error\n");
		return -1;
	}

	/* close the file descriptor */
	if (close(src_fd) == -1) {
		fprintf(stderr, "copy: close src_fd\n");
		return -1;
	}
	if (close(dest_fd) == -1) {
		fprintf(stderr, "copy: close dest_fd\n");
		return -1;
	}

	printf("copy done!\n");
	return 0;
}
